import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { login, getUserInfo } from '@/api/user'
import router from '@/router'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}
const actions = {
  async login(context, data) {
    // 1.发送请求
    // 2.获取token
    const res = await login(data)
    console.log(res.data.token)
    // 3.调用mutation
    context.commit('setToken', res.data.token)
    // 提示登录成功
    Message.success('登录成功')
    // 跳转到首页
    router.push('/')
  },
  logout(context) {
    context.commit('removeToken') // 清除token
    context.commit('setUserInfo', {}) // 清除用户信息
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
